package com.lm.redisson.controller;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/lock")
public class LockController {

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/test")
    public String testLock() {
        RLock lock = redissonClient.getLock("order-lock");

        try {
            // 尝试获取锁，最多等待 2 秒，获得锁后 10 秒自动释放
            if (lock.tryLock(2, 10, TimeUnit.SECONDS)) {
                System.out.println("获取锁成功，开始执行业务逻辑...");
                Thread.sleep(3000);
                return "success";
            } else {
                return "获取锁失败，请稍后重试";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
